<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active {
      color: red;
    }
  </style>
</head>

<body>
  <div id="app">
    <router-link to="/home" tag="button">首页</router-link>
    <router-link to="/news" tag="button">新闻</router-link>
    <router-link to="/about" tag="button">关于我们</router-link>
    <router-view />
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 创建 路由组件option
    const Home = {
      template: `
        <div>
          <h2>首页</h2>  
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>新闻</h2>  
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h2>关于我们</h2>  
        </div>
      `
    }
    const NotFound = {
      template: `
        <div>
          <h2>404了</h2>  
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h2>登录页</h2>  
          <button @click="doLogin">点击登录</button>
        </div>
      `,
      methods: {
        doLogin() {
          setTimeout(() => {
            const token = 'dwfeghir34t5g';
            // 立即缓存
            localStorage.setItem('token', token);
            // 跳转到目标路由 
            if(this.$route.query.from){
              this.$router.replace(this.$route.query.from)
            }else{
              this.$router.replace('/home')
            }
          }, 1000)
        }
      }
    }
    const routes = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
      {
        path: '/news',
        alias: '/a',
        component: News
      },
      {
        path: '/about',
        component: About,
        beforeEnter(to, from, next){
          /* 
            判断有没有token 
            有 放行
            没有 去登录
          */
         const token = localStorage.getItem('token');
         if(token){
           next();
         }else{
           next({
             path: '/login',
             query: {
               from: '/about'
             }
           })
         }
        }
      },
      {
        path: '/login',
        component: Login
      },
      {
        path: '*',
        component: NotFound
      }
    ]
    //  创建router 实例
    const router = new VueRouter({
      routes
    })
  
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>

</html>